#ifdef RFID
//*********************************************************************************************/
// Defines for variables used by this userplugin
//*********************************************************************************************/

#define RFID_USEREVENT             200

//===================================================================================================================================
// End of user configurable settings, do not change anything below this section!
//===================================================================================================================================
#ifdef RFID
#ifdef ARDUINO_0022
#include <NewSoftSerial.h>
NewSoftSerial rfid(7,255);
#else
#include <SoftwareSerial.h>
SoftwareSerial rfid(7,255);
#endif
byte userPluginRFIDIndex=1;
#define USERPLUGIN_EEPROM_RFIDBASE 900
#endif

/*********************************************************************************************\ 
 * Dit deel van de plugin wordt eenmalig aangeroepen direct na boot en tonen welkomsttekst
 \*********************************************************************************************/
void UserPlugin_RFID_Init(void)
{
  pinMode(7,INPUT);
  rfid.begin(9600);
  rfid.listen();
}

/*********************************************************************************************\ 
 * Dit deel van de plugin wordt aangeroepen met het Nodo commando "UserPlugin Par1,Par2"
 * 
 * TIPS:
 * - Par1 en Par2 zijn twee parameters die je kunt meegeven. Deze kunnen beide een waarde hebben van 0..255
 * - De userplugin kan worden aangeroepen als commando of als actie vanuit de eventlist.
 * - Gebruikersvariabelen kunnen worden gelezen, waarbij S.UserVar[0] gelijk is aan de eerste gebruikersvariabele.
 \*********************************************************************************************/

void UserPlugin_RFID_Command(int Par1, int Par2)
{
  if (Par1 == 200) userPluginRFIDIndex = Par2;

  if ((Par1 >= 201) && (Par1 <=205)) EEPROM.write(USERPLUGIN_EEPROM_RFIDBASE + ((userPluginRFIDIndex-1) *5) + Par1-201, Par2);

  if ((Par1 >= 200) && (Par1 <=205))
  {
    TempString[0]=0;
    strcat(TempString,"RFID Valid Tag ");
    strcat(TempString,int2str(userPluginRFIDIndex));
    strcat(TempString,":");
    for (byte x=0; x<5; x++)
    {
      strcat(TempString,int2str(EEPROM.read(USERPLUGIN_EEPROM_RFIDBASE + ((userPluginRFIDIndex-1) *5) + x)));
      strcat(TempString,",");
    }
    userPluginPrintTerminal(TempString);
  }
}

boolean UserPlugin_RFID_Receive(unsigned long Event)
{
  byte code=0;
  byte command = (Event >> 16) & 0xff;
  byte par1    = (Event >> 8) & 0xff;
  byte par2    = (Event) & 0xff;
  
  if ((command == CMD_USEREVENT) && (par1 == 200))
  {
    #ifdef LCD_I2C
      lcdprintline(0,"Alarm");
      if (par2 == 100) lcdprintline(1,"Uitgeschakeld");
      if (par2 == 101) lcdprintline(1,"Ingeschakeld"); 
    #endif
  }

  // funktie kan op twee manieren worden verlaten:
  // true = Nodo gaat verder met verwerking van het event
  // false = Event wordt niet verder behandeld.
  if (code == 0) return true;
  return false;
}


void UserPlugin_RFID_Periodically()
{
  rfidloop();
  return;
}

/*********************************************************************************************\
 * RFID stuff
 \*********************************************************************************************/
boolean rfidloop () {
  byte i = 0;
  byte val = 0;
  byte code[6];
  byte checksum = 0;
  byte bytesread = 0;
  byte tempbyte = 0;
  byte validrfid = 0;
  byte rfidbyte =0;

  if(rfid.available() > 0) {
    if((val = rfid.read()) == 2) {                  // check for header 
      bytesread = 0; 
      while (bytesread < 12) {                        // read 10 digit code + 2 digit checksum
        if( rfid.available() > 0) { 
          val = rfid.read();
          if((val == 0x0D)||(val == 0x0A)||(val == 0x03)||(val == 0x02)) { // if header or stop bytes before the 10 digit reading 
            break;                                    // stop reading
          }

          // Do Ascii/Hex conversion:
          if ((val >= '0') && (val <= '9')) {
            val = val - '0';
          } 
          else if ((val >= 'A') && (val <= 'F')) {
            val = 10 + val - 'A';
          }

          // Every two hex-digits, add byte to code:
          if (bytesread & 1 == 1) {
            // make some space for this hex-digit by
            // shifting the previous hex-digit with 4 bits to the left:
            code[bytesread >> 1] = (val | (tempbyte << 4));

            if (bytesread >> 1 != 5) {                // If we're at the checksum byte,
              checksum ^= code[bytesread >> 1];       // Calculate the checksum... (XOR)
            };
          } 
          else {
            tempbyte = val;                           // Store the first hex digit first...
          };

          bytesread++;                                // ready to read next digit
        } 
      } 

      // Output to Serial:

      if (bytesread == 12) {                          // if 12 digit read is complete
        Serial.print("5-byte code: ");
        for (i=0; i<5; i++) {
          if (code[i] < 16) Serial.print("0");
          Serial.print(code[i], DEC);
          Serial.print(" ");
        }
        Serial.println();

        Serial.print("Checksum: ");
        Serial.print(code[5], DEC);
        Serial.println(code[5] == checksum ? " -- passed." : " -- error.");
        Serial.println();

        for (byte x=0; x<10; x++)
        {
          Serial.print("Checking RFID Tag:");
          Serial.println((int)x+1);
          validrfid = 0;
          for (byte i=0; i<5; i++)
          {
            rfidbyte = EEPROM.read(USERPLUGIN_EEPROM_RFIDBASE + (x*5) + i);
            Serial.print((int)rfidbyte);
            Serial.print("-");
            Serial.println((int)code[i]);          
            if (rfidbyte == code[i]) validrfid++;
          }
          if (validrfid == 5)
          {
            Serial.println("Valid RFID!!");
            #ifdef LCD_I2C
              lcdprintline(0,"Valid Tag!");
              lcdprintline(1,""); 
            #endif 
            Beep(1000,500);

#ifdef NODO_CLASSIC
            Nodo_2_RawSignal(command2event(CMD_USER_EVENT,RFID_USEREVENT,1));
#else
            Nodo_2_RawSignal(command2event(Settings.Unit,CMD_USEREVENT,RFID_USEREVENT,1));
#endif
            RawSendRF();
            return true;
          }
        }
      }
      Serial.println("Invalid RFID!!");
      #ifdef LCD_I2C
        lcdprintline(0,"InValid Tag!");
        lcdprintline(1,"");
      #endif 
      Beep(2000,2000);
      bytesread = 0;
    }
  }
  return false;
}
#endif

